package cn.edu.gzmtu.controller;

import cn.edu.gzmtu.domain.Role;
import cn.edu.gzmtu.domain.UserInfo;
import cn.edu.gzmtu.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * 用户管理模块：用户查询、添加操作
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 查询所有用户
     * @return
     * @throws Exception
     */
    @RequestMapping("/findAll.do")
    // @Secured("ROLE_ADMIN") // 不能省略前缀"ROLE_"
    @PreAuthorize("hasRole('ROLE_ADMIN')") // 具备ADMIN权限可以访问
    public ModelAndView findAll() throws Exception {
        ModelAndView mv = new ModelAndView();

        List<UserInfo> userList = userService.findAll();

        mv.addObject("userList", userList);
        mv.setViewName("user-list");

        return mv;
    }

    /**
     * 添加用户
     * @param userInfo
     * @throws Exception
     */
    @RequestMapping("/save.do")
    @PreAuthorize("authentication.principal.username =='azhuo'") // 用户名为"azhuo"可以执行操作
    public String save(UserInfo userInfo) throws Exception{

        userService.save(userInfo);

        return "redirect:findAll.do";
    }

    /**
     * 根据id查询用户
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("/findById.do")
    public ModelAndView findById(@RequestParam(required = true) String id) throws Exception{

        UserInfo userInfo = userService.findById(id);

        ModelAndView mv = new ModelAndView();
        mv.addObject("user", userInfo);
        mv.setViewName("user-show");
        return mv;
    }

    /**
     * 根据id查询 已有的角色 和 未具有的角色
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping("/findUserByIdAndAllRole.do")
    public ModelAndView findUserByIdAndAllRole(@RequestParam(name = "id", required = true) String userId) throws Exception {
        // 根据用户id查询用户
        UserInfo userInfo = userService.findById(userId);

        // 根据用户id查询可以添加的角色
        List<Role> otherRoles = userService.findUserOtherRoles(userId);

        ModelAndView mv = new ModelAndView();
        mv.addObject("user", userInfo);
        mv.addObject("roleList", otherRoles);
        mv.setViewName("user-role-add");

        return mv;
    }

    /**
     * 给用户添加权限
     * @param userId
     * @param roleIds
     * @return
     */
    @RequestMapping("/addRoleToUser.do")
    public String addRoleToUser(@RequestParam(name = "userId", required = true) String userId, @RequestParam(name = "ids", required = true) String[] roleIds) throws Exception {

        userService.addRoleToUser(userId, roleIds);

        return "redirect:findAll.do";
    }
}
